import { BrowserRouter as Router, Routes, Route, Navigate, Outlet } from 'react-router-dom';
import { AuthProvider, useAuth } from './context/AuthContext';

import Navbar from './components/Navbar'
import Footer from './components/Footer'
import ScrollProgress from './components/ScrollProgress'
import BackToTop from './components/BackToTop'
import HomePage from './pages/HomePage'
import LoginPage from './pages/LoginPage'
import RegisterPage from './pages/RegisterPage'
import ProfilePage from './pages/ProfilePage'
import InstallGuidePage from './pages/InstallGuidePage'
import './App.css'

// 路由守卫：已登录用户才能访问
const ProtectedRoute = () => {
  const { isAuthenticated, isLoading } = useAuth();
  if (isLoading) return <div>加载中...</div>;
  return isAuthenticated ? <Outlet /> : <Navigate to="/login" replace />;
};

// 路由守卫：未登录用户才能访问（例如登录页、注册页）
const PublicRoute = () => {
  const { isAuthenticated, isLoading } = useAuth();
  if (isLoading) return <div>加载中...</div>;
  return isAuthenticated ? <Navigate to="/profile" replace /> : <Outlet />;
};

// 主应用布局
const MainLayout = () => (
  <div className="App">
    <ScrollProgress />
    <Navbar />
    <main>
      <Outlet />
    </main>
    <Footer />
    <BackToTop />
  </div>
);

function App() {
  return (
    <AuthProvider>
      <Router>
        <Routes>
          <Route element={<MainLayout />}>
            {/* 公共路由，所有人都能访问 */}
            <Route path="/" element={<HomePage />} />
            <Route path="/install-guide" element={<InstallGuidePage />} />

            {/* 访客路由，只有未登录用户能访问 */}
            <Route element={<PublicRoute />}>
              <Route path="/login" element={<LoginPage />} />
              <Route path="/register" element={<RegisterPage />} />
            </Route>

            {/* 受保护路由，只有已登录用户能访问 */}
            <Route element={<ProtectedRoute />}>
              <Route path="/profile" element={<ProfilePage />} />
            </Route>
          </Route>
        </Routes>
      </Router>
    </AuthProvider>
  )
}

export default App


